<?

namespace core;
use Swoole\Coroutine\Http\Server;
use function Swoole\Coroutine\run;
use Swoole\Process;
use Swoole\Timer;
use app\Bootstrap;

class Srv 
{
    public static $server = null;

    public static $handler = null;
    
    public static $cache = [];

    public static function start()
    {
        $option = include_once BASE_PATH.'/app/server.php';
        run(function()use($option){
            ini_set('memory_limit', '1G');
            cli_set_process_title(APP_NAME);
            loger(posix_getpid());
            file_put_contents(BASE_PATH.'/runtime/server.pid', posix_getpid());
            Bootstrap::start();
            self::$server = new Server('0.0.0.0', APP_PORT,false,true);
            self::$server->set($option);
            self::$server->handle('/',fn($t,$e)=>self::http($t,$e));
            self::$server->handle('/chat',fn($t,$e)=>self::websocket($t,$e));
            self::$server->start();
        });
    }

    public static function dev()
    {

        $p = new Process(function(){
            cli_set_process_title('watcher');
            $lt = time();

            while (true) {
                \core\Bin::pf(BASE_PATH.'/app',function($f)use(&$lt){
                    if (filemtime($f)>$lt) {
                        loger($f.' change ');
                        $lt = time();
                        self::start();
                    }
                });
                sleep(1);
            }
        });
        $p->daemon();
        $p->start();
        
        loger($p);
    }

    public static function http($request, $response)
    {
       
        $response->header('Server', 'LimServer');
        
        if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {

            return $response->end();
        }

        switch ($request->server['request_method']) {
            case 'OPTIONS':
                $response->header('Access-Control-Allow-Origin', '*');
                $response->header('Access-Control-Allow-Methods', '*');
                $response->header('Access-Control-Allow-Headers', '*');
                return $response->end();
            case 'GET':
                $data = $request->get;
                break;
            case 'POST':
                $data= $request->post ?? json_decode($request->getContent(), true);
                break;
            default:
                return $response->end();
        }
        app('curr')->request = $request;
        app('curr')->response = $response;
        app('curr')->data = $data;
        try {
            $uri = substr($request->server['request_uri'], 1);
            if ($o=$GLOBALS['config']['router'][$uri]??null) {
                $data = $GLOBALS['config']['interface'][$o['controller']]->{$o['method']}($data);
                json($data);
            } else {
                json(null,'路由不存在',3001);
            }
        } catch (\Throwable $e) {
            json(null,$e->getMessage(),$e->getCode());
        }
    }

    public static function websocket($request, $ws)
    {
        loger($request);
        $ws->upgrade();
        while (true) {
            $frame = $ws->recv();
            loger($frame);
            if ($frame === '' || $frame === false) {
                loger($frame);
                $ws->close();
                break;
            }
            $ws->push("Hello {$frame->data}!");
        }
    }
}

